//
//  FMSServerAPI.m
//  FMS
//
//  Created by Steven on 10/19/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "FMSServerAPI.h"
#import "AFJSONRequestOperation.h"
#import "NSData+Extension.h"
#import "NSString+Extension.h"

@interface FMSServerAPI (PrivateMethods)
- (void) postErrorNotification: (NSError*) error;
- (NSURL*)buildRESTFULLUrlWithURL:(NSURL *)url arguments:(NSDictionary*)arguments;
- (void)getPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure;
- (void)postPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure;

- (void)getPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes authenticationUserEmail:(NSString *)userEmail password:(NSString *)password error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure;

- (void)postPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes authenticationUserEmail:(NSString *)userEmail password:(NSString *)password error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure;

@end

@implementation FMSServerAPI (PrivateMethods)

- (void) postErrorNotification: (NSError*) error
{
    NSNotification *note;
    if (error) {
        note = [NSNotification notificationWithName:mServerRequestError
                                             object:[NSDictionary dictionaryWithObject:error forKey:@"error"]];
    }
    else {
        note = [NSNotification notificationWithName:mServerRequestError
                                             object:nil];
    }
    [[NSNotificationCenter defaultCenter] performSelectorOnMainThread:@selector(postNotification:)
                                                           withObject:note
                                                        waitUntilDone:YES];
}

- (NSURL *) buildRESTFULLUrlWithURL:(NSURL *)url arguments:(NSDictionary*)arguments
{
	// Build arguments string
    NSMutableArray *argumentsArray = [NSMutableArray array];
    for (NSString *key in arguments) {
        NSString *value = [[arguments objectForKey:key] description];
        
        NSString *safeKey = [key stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
        NSString *safeValue = [value stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
        
        [argumentsArray addObject:[NSString stringWithFormat:@"%@=%@", safeKey, safeValue]];
    }
    NSString *argumentsString = [argumentsArray componentsJoinedByString:@"&"];
    return [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", [url absoluteString], argumentsString]];
}

- (void)getPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
    NSParameterAssert(pathAPI);
    
    if (ntimes<=0) {
        [self postErrorNotification:error];
        if (failure) {
            failure(error);
        }
    } else {
        NSMutableURLRequest *httpReq = [[NSMutableURLRequest alloc] initWithURL:[self buildRESTFULLUrlWithURL:[NSURL URLWithString:[self.baseURL append:pathAPI]] arguments:arguments]];
        LOGAPP(@">>> Http Request: %@", httpReq);
        
        [httpReq setHTTPMethod:@"GET"];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary * parsedResults = nil;
                if (self.responseType == ServerResponseTypeJSON) {
                    parsedResults = [responseObject jsonStringToDictionary];
                }
                
                if ($safe(parsedResults)) {
                    if (success) {
                        success(parsedResults);
                    }
                } else {
                    if (success) {
                        success(responseObject);
                    }
                }
                
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self getPath:pathAPI arguments:arguments withRetry:ntimes-1 error:error success:success failure:failure];
        }];
        
        [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
            if ([challenge previousFailureCount] == 0) {
                [[challenge sender]  useCredential:[NSURLCredential credentialWithUser:_userName password:_password
                                                                           persistence:NSURLCredentialPersistenceNone]
                        forAuthenticationChallenge:challenge];
                
            } else {
                [[challenge sender] cancelAuthenticationChallenge:challenge];
            }
        }];
        
        [operation start];
        //[self.apiClient.operationQueue addOperation:operation];
    }
}

- (void)postPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
    NSParameterAssert(pathAPI);
    
    if (ntimes<=0) {
        [self postErrorNotification:error];
        if (failure) {
            failure(error);
        }
    } else {
        NSMutableURLRequest *httpReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[self.baseURL append:pathAPI]]];//[ autorelease];
        
        LOGAPP(@"Http Request: %@", httpReq);
        
        [httpReq setHTTPMethod:@"POST"];
        //NSArray*keys=[arguments allKeys];
        NSString *body = @"";
        LOGAPP(@"count keys %i",[[arguments allKeys] count]);
        for(int i = 0;i<[[arguments allKeys] count];i++)
        {
            NSString *key = [NSString stringWithFormat:@"%@",[[arguments allKeys] objectAtIndex:i]];
            
            BOOL isYES = (i == [[arguments allKeys] count] - 1);
            
            NSString *value = [NSString stringWithFormat:isYES?@"%@=%@":@"%@=%@&",key,[arguments valueForKey:key]];
            
            body = [body stringByAppendingString:value];
        }
        //LOGAPP(@"body %@",body);
        [httpReq setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary * parsedResults = nil;
                if (self.responseType == ServerResponseTypeJSON) {
                    parsedResults = [responseObject jsonStringToDictionary];
                }
                
                if ($safe(parsedResults)) {
                    if (success) {
                        success(parsedResults);
                    }
                } else {
                    if (success) {
                        success(responseObject);
                    }
                }
                
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self postPath:pathAPI arguments:arguments withRetry:ntimes-1 error:error success:success failure:failure];
        }];
        
        [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
            if ([challenge previousFailureCount] == 0) {
                [[challenge sender]  useCredential:[NSURLCredential credentialWithUser:_userName password:_password
                                                                           persistence:NSURLCredentialPersistenceNone]
                        forAuthenticationChallenge:challenge];
                
            } else {
                [[challenge sender] cancelAuthenticationChallenge:challenge];
            }
        }];
        
        [operation start];
    }
}

- (void)getPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes authenticationUserEmail:(NSString *)userEmail password:(NSString *)password error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure{
    
    NSParameterAssert(pathAPI);
    
    if (ntimes<=0) {
        [self postErrorNotification:error];
        if (failure) {
            failure(error);
        }
    } else {
        NSMutableURLRequest *httpReq = [[NSMutableURLRequest alloc] initWithURL:[self buildRESTFULLUrlWithURL:[NSURL URLWithString:[self.baseURL append:pathAPI]] arguments:arguments]];
        LOGAPP(@">>> Http Request: %@", httpReq);
        
        [httpReq setHTTPMethod:@"GET"];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary * parsedResults = nil;
                if (self.responseType == ServerResponseTypeJSON) {
                    parsedResults = [responseObject jsonStringToDictionary];
                }
                
                if ($safe(parsedResults)) {
                    if (success) {
                        success(parsedResults);
                    }
                } else {
                    if (success) {
                        success(responseObject);
                    }
                }
                
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self getPath:pathAPI arguments:arguments withRetry:ntimes-1 error:error success:success failure:failure];
        }];
        
        [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
            if ([challenge previousFailureCount] == 0) {
                [[challenge sender]  useCredential:[NSURLCredential credentialWithUser:userEmail password:password
                                                                           persistence:NSURLCredentialPersistenceNone]
                        forAuthenticationChallenge:challenge];
                
            } else {
                [[challenge sender] cancelAuthenticationChallenge:challenge];
            }
        }];
        
        [operation start];
        //[self.apiClient.operationQueue addOperation:operation];
    }

    
}

- (void)postPath:(NSString*)pathAPI arguments:(NSDictionary*)arguments withRetry:(int)ntimes authenticationUserEmail:(NSString *)userEmail password:(NSString *)password error:(NSError*)error success:(void (^)(id response))success failure:(void (^)(NSError *error))failure
{
    NSParameterAssert(pathAPI);
    
    if (ntimes<=0) {
        [self postErrorNotification:error];
        if (failure) {
            failure(error);
        }
    } else {
        NSMutableURLRequest *httpReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[self.baseURL append:pathAPI]]];//[ autorelease];
        
        LOGAPP(@"Http Request: %@", httpReq);
        
        [httpReq setHTTPMethod:@"POST"];
        //NSArray*keys=[arguments allKeys];
        NSString *body = @"";
        LOGAPP(@"count keys %i",[[arguments allKeys] count]);
        for(int i = 0;i<[[arguments allKeys] count];i++)
        {
            NSString *key = [NSString stringWithFormat:@"%@",[[arguments allKeys] objectAtIndex:i]];
            
            BOOL isYES = (i == [[arguments allKeys] count] - 1);
            
            NSString *value = [NSString stringWithFormat:isYES?@"%@=%@":@"%@=%@&",key,[arguments valueForKey:key]];
            
            body = [body stringByAppendingString:value];
        }
        //LOGAPP(@"body %@",body);
        [httpReq setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([responseObject isKindOfClass:[NSData class]]) {
                NSDictionary * parsedResults = nil;
                if (self.responseType == ServerResponseTypeJSON) {
                    parsedResults = [responseObject jsonStringToDictionary];
                }
                
                if ($safe(parsedResults)) {
                    if (success) {
                        success(parsedResults);
                    }
                } else {
                    if (success) {
                        success(responseObject);
                    }
                }
                
                
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self postPath:pathAPI arguments:arguments withRetry:ntimes-1 error:error success:success failure:failure];
        }];
        
        [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
            if ([challenge previousFailureCount] == 0) {
                [[challenge sender]  useCredential:[NSURLCredential credentialWithUser:userEmail password:password
                                                                           persistence:NSURLCredentialPersistenceNone]
                        forAuthenticationChallenge:challenge];
                
            } else {
                [[challenge sender] cancelAuthenticationChallenge:challenge];
            }
        }];
        
        [operation start];
    }
}
@end


@implementation FMSServerAPI

static FMSServerAPI *serverAPI = nil;
@synthesize baseURL;
@synthesize responseType;
+ (FMSServerAPI *)shareClient{
    @synchronized(serverAPI)
    {
        if(serverAPI == nil)
            serverAPI = [[FMSServerAPI alloc] initWithBaseURL:[[NSUserDefaults standardUserDefaults] objectForKey:SERVER_KEY]];
    }

    return serverAPI;
}
+ (FMSServerAPI *)changeServerLink:(NSString *)serverLink{
    @synchronized(serverAPI)
    {
        serverAPI = [[FMSServerAPI alloc] initWithBaseURL:serverLink];
    }
    return serverAPI;
}
- (id)initWithBaseURL:(NSString *)url {
    self = [super init];
    if (!self) {
        return nil;
    }
    self.baseURL = url;
    return self;
}
- (void)setUserName:(NSString *)userName password:(NSString *)password{
    _userName = userName;
    _password = password;
}
#pragma mark server methods
static int getPrimaryNumb(int index){
    if(index >= 5000)
        return -1;
    
    BOOL isOk = false;
    int j = 1;
    int i = 0;
    while(i < 5001)
    {
        isOk = false;
        while(!isOk){
            j++;
            //            int sqr = (int)Math.sqrt((double)j) + 1;
            int sqr = (int)sqrt((double)j) + 1;
            isOk = true;
            for(int k = 2; k < sqr; k++){
                if(j%k == 0){
                    isOk = false;
                    break;
                }
            }
        }
        
        if(i == index)
            return j;
        i++;
    }
    return -1;
}

+ (NSString*) decrypt:(NSString*)encodedString{
    NSString *decodedString = @"";
    
    // seperate character
    char seperate = 67;
    
    NSString *regex = [NSString stringWithFormat:@"%c",seperate];
    NSArray *arrEncoded = [encodedString componentsSeparatedByString:regex];
    NSString *split = [NSString stringWithFormat:@"%c",(char)66];
    
    for (int i=0;i < [arrEncoded count]-1;i++){
        NSString *iter = [arrEncoded objectAtIndex:i];
        NSArray *arrChar = [iter componentsSeparatedByString:split];
        
        NSString *cSplit = [NSString stringWithFormat:@"%c",(char)65];
        NSArray *arrInfor = [[arrChar objectAtIndex:1] componentsSeparatedByString:cSplit];
        
        int pLength = [arrInfor count];
        int pIndex = 0;
        
        for(int i = pLength - 1; i >= 0 ; i--){
            NSString *s = [arrInfor objectAtIndex:i];
            int c = [s intValue];
            pIndex = (pIndex * 249 + c);
        }
        
        pIndex^= 65535; // 65535
        
        NSArray *arrKey = [[arrChar objectAtIndex:0] componentsSeparatedByString:cSplit];
        int length = [arrKey count];
        // get primary number index
        
        int oNumb = 0; // original numb;
        for(int i = length -1 ; i >= 0 ; i--){
            NSString *s = [arrKey objectAtIndex:i];
            int c = [s intValue];
            oNumb = oNumb * 249 + c;
            
        }
        oNumb^= getPrimaryNumb(pIndex)^ 65535;//65535
        oNumb^= 255; // 255
        char c= (char)oNumb;
        decodedString = [decodedString stringByAppendingString:[NSString stringWithFormat:@"%c",c]];
    }
    //NSlog(@"decodeString = %@",decodedString);
    return decodedString;
}

- (void)getDomainInfo:(NSString *)virtualHost successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    
    NSURL *url = [NSURL URLWithString:self.baseURL];
    
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    
    [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
	[httpClient setDefaultHeader:@"Accept" value:@"application/json"];
    
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/api/user/get_auth_account_encrypted" parameters:nil];
    [request setTimeoutInterval:200];
    
    AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) {
        NSDictionary * parsedResults = nil;
        parsedResults = (NSMutableDictionary *)response;
        
        if ([[[parsedResults objectForKey:@"meta"] objectForKey:@"code"] intValue] == 200) {
            //success
            successs(parsedResults);
        }
        //failed
        else{
            NSString * errorDesc = @"Invalid response data";
            NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"invalid request",@"title",
                                        errorDesc,@"description",nil];
            NSError * error = [NSError errorWithDomain:kFMSServerDomain code:0 userInfo:errorDict];
            failure(error);
        }
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[FMSServerAPI shareClient] setUserName:@"" password:@""];
        NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"request faile",@"title",
                                    error.debugDescription,@"description",nil];
        error = [NSError errorWithDomain:kFMSServerDomain code:0 userInfo:errorDict];
        failure(error);
    }];
    
    [operation start];
    [operation waitUntilFinished];
    
//    NSURLResponse *response = nil;
//    NSError *error = nil;
//    
//    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
//    
//    httpClient.parameterEncoding = AFFormURLParameterEncoding;
//    
//    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/api/user/get_auth_account_encrypted" parameters:nil];
//    
//    NSData *responseObject;
//    int countTimeOut = 0;
//    do {
//        responseObject = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//        countTimeOut++;
//    } while (error && countTimeOut < 3);
//    
//
//    if (error) {
//        [[FMSServerAPI shareClient] setUserName:@"" password:@""];
//        NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"request faile",@"title",
//                                    error.debugDescription,@"description",nil];
//        NSError * error = [NSError errorWithDomain:kFMSServerDomain code:0 userInfo:errorDict];
//        failure(error);
//    }
//    else{
//        if ([responseObject isKindOfClass:[NSData class]]) {
//            NSDictionary * parsedResults = nil;
//            parsedResults = [responseObject jsonStringToDictionary];
//            
//            if ([[[parsedResults objectForKey:@"meta"] objectForKey:@"code"] intValue] == 200) {
//                //success
//                successs(parsedResults);
//            }
//            //failed
//            else{
//                NSString * errorDesc = @"Invalid response data";
//                NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"invalid request",@"title",
//                                            errorDesc,@"description",nil];
//                NSError * error = [NSError errorWithDomain:kFMSServerDomain code:0 userInfo:errorDict];
//                failure(error);
//            }
//        }
//    }
    
    
}
- (void)getCompanyId:(NSString *)virtualHost successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    
    NSMutableDictionary *argumentsServer = [NSMutableDictionary dictionaryWithObjectsAndKeys:virtualHost,@"domain", nil];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    
    NSURL *url = [NSURL URLWithString:self.baseURL];
    
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    
    httpClient.parameterEncoding = AFFormURLParameterEncoding;
    
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/QGSConfig-portlet/api/jsonws/userauthenticate/fetchByDomain" parameters:argumentsServer];
    NSData *responseObject = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
//    NSError *error = nil;
//    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:self.baseURL]];
//    id responseObject = [client synchronouslyGetPath:@"/QGSConfig-portlet/api/jsonws/userauthenticate/fetchByDomain" parameters:argumentsServer operation:nil error:&error];
    if (error) {
        [[FMSServerAPI shareClient] setUserName:@"" password:@""];
        NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"request faile",@"title",
                                    error.debugDescription,@"description",nil];
        NSError * error = [NSError errorWithDomain:kFMSServerDomain code:0 userInfo:errorDict];
        failure(error);
    }
    else{
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSDictionary * parsedResults = nil;
            parsedResults = [responseObject jsonStringToDictionary];
            
            NSString *adminUsername = [parsedResults objectForKey:@"email"];
            NSString *adminPassword = [parsedResults objectForKey:@"password"];
            if(adminUsername == nil || adminPassword == nil || [adminUsername isEqualToString:@""] || [adminPassword isEqualToString:@""])
            {
                NSString * errorDesc = @"Invalid response data";
                NSDictionary * errorDict = [NSDictionary dictionaryWithObjectsAndKeys:@"invalid request",@"title",
                                            errorDesc,@"description",nil];
                NSError * error = [NSError errorWithDomain:kFMSServerDomain code:0 userInfo:errorDict];
                failure(error);
            }
            else
            {
                adminUsername = [FMSServerAPI decrypt:adminUsername];
                adminPassword = [FMSServerAPI decrypt:adminPassword];
                
                [[FMSServerAPI shareClient] setUserName:adminUsername password:adminPassword];
                
                NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:virtualHost,@"virtualHost", nil];
                self.responseType = ServerResponseTypeJSON;
                [self getPath:@"/api/secure/jsonws/company/get-company-by-virtual-host"  arguments:arguments withRetry:requestRetryLimit error:nil success:successs failure:failure];
            }
        }
    }
    
   
}
//get time duration to limit data
- (void)getTimeDurationSuccess:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    self.responseType = ServerResponseTypeJSON;
    
    [self postPath:@"/api/user/get_time_duration" arguments:nil withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

- (void)checkPermissionUser:(NSString *)user auth:(NSString *)auth success:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    NSMutableDictionary *argumentsServer = [NSMutableDictionary dictionaryWithObjectsAndKeys:user,@"username",auth,@"password", nil];
    
    self.responseType = ServerResponseTypeJSON;
    [self postPath:@"/api/user/checkPermissionDeleteDb" arguments:argumentsServer withRetry:requestRetryLimit error:nil success:successs failure:failure];
}


#pragma mark user methods
//user info in sql
- (void)getUserInfoAuthenticationUserEmail:(NSString *)userEmail password:(NSString *)password fromCompnay:(int)companyId success:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    self.responseType = ServerResponseTypeJSON;
    
    NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:companyId],@"companyId",userEmail,@"emailAddress", nil];
    
    [self getPath:@"/api/secure/jsonws/user/get-user-by-email-address" arguments:arguments withRetry:3 authenticationUserEmail:userEmail password:password error:nil success:successs failure:failure];
}


//user info in couchdb
- (void)loginWithUser:(NSString *)userEmail password:(NSString *)password successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:userEmail,@"username",password,@"password", nil];
    self.responseType = ServerResponseTypeJSON;
    [self postPath:@"/api/user/login" arguments:arguments withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

- (void)forgotPasswordEmail:(NSString *)userEmail successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:userEmail,@"username", nil];
    self.responseType = ServerResponseTypeJSON;
    [self postPath:@"/api/user/forgotPassword" arguments:arguments withRetry:requestRetryLimit error:nil success:successs failure:failure];
}
//get Owner info database
- (void)getOwnerUserInfoByEmail:(NSString *)email success:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:email,@"email", nil];
    self.responseType = ServerResponseTypeJSON;
    [self postPath:@"/DataCouchDB-portlet/api/secure/jsonws/ownerinfo/findByEmail" arguments:arguments withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

#pragma mark building methods
- (void)getAllBuildingSuccesss:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    
    [self postPath:@"/api/building/get_all_building" arguments:nil withRetry:requestRetryLimit error:nil success:successs failure:failure];
    
}

- (void)getBuildingInfoByBuidingId:(NSString *)buildingId successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:buildingId,@"buildingId", nil];
    [self postPath:@"/api/building/get_building_info_by_id" arguments:arguments  withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

- (void)getBuildingInfoByName:(NSString *)buildingName successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure{
    NSMutableDictionary *arguments = [NSMutableDictionary dictionaryWithObjectsAndKeys:buildingName,@"buildingName", nil];
    [self postPath:@"/api/building/get_building_info_by_name" arguments:arguments  withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

#pragma mark Get eForm for Maintenance
- (void) getEformByType:(NSMutableDictionary*)_argument successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure {

    self.responseType = ServerResponseTypeJSON;
    
    [self postPath:@"/api/document/get_document_info_by_type" arguments:_argument withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

- (void) getDetailedEform:(NSMutableDictionary*)_argument successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure {
    self.responseType = ServerResponseTypeJSON;
    
    [self postPath:@"/api/maintenance/getEformMaintenance" arguments:_argument withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

- (void) saveEform:(NSMutableDictionary*)_arguments successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure {

    self.responseType = ServerResponseTypeJSON;
    
    [self postPath:@"/api/maintenance/saveMaintenance" arguments:_arguments withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

- (void) sendEmailMaintenance:(NSMutableDictionary*)_arguments successs:(void (^)(id response))successs failure:(void (^)(NSError *error))failure {
    
    self.responseType = ServerResponseTypeJSON;
    
    [self postPath:@"/api/maintenance/sendEmailMaintanance" arguments:_arguments withRetry:requestRetryLimit error:nil success:successs failure:failure];
}

@end
